package bma.common.thrift.xdom;

import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TMessageType;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TType;

import bma.common.langutil.xdom.Xdom;
import bma.common.langutil.xdom.core.XdomMap;
import bma.common.langutil.xdom.core.XdomNULL;

public abstract class TProcessorXdom implements TProcessor {

	private DynamicThriftManager descManager;

	public DynamicThriftManager getDescManager() {
		return descManager;
	}

	public void setDescManager(DynamicThriftManager descManager) {
		this.descManager = descManager;
	}

	@Override
	public boolean process(TProtocol in, TProtocol out) throws TException {
		TMessage msg = in.readMessageBegin();
		String name = msg.name;
		int idx = name.indexOf('.');
		if (idx != -1) {
			name = name.substring(idx + 1);
		}
		TDynamicFunction f = descManager.getFunction(name);
		if (f == null)
			throw new TException("unknow function '" + name + "'");
		Reader reader = new Reader(f.getManager());
		Xdom param = reader.readStruct(f.getParamStruct(), in);
		in.readMessageEnd();

		if (!f.isOneway()) {

			XdomMap rep;
			TDynamicField retf = f.getReturnStruct().getField("success");
			if (retf.getTypeValue() != TType.VOID) {
				Xdom ret = handle(name, param);
				rep = new XdomMap();
				rep.put("success", ret);
			} else {
				rep = new XdomMap();
			}

			TMessage repmsg = new TMessage(name, TMessageType.REPLY, msg.seqid);
			out.writeMessageBegin(repmsg);
			Writer writer = new Writer(f.getManager());
			writer.writeStruct(f.getReturnStruct(), rep, out);
			out.writeMessageEnd();
			out.getTransport().flush();
		}
		return true;
	}

	public abstract Xdom handle(String name, Xdom param);
}
